/**
 * 左边导航
 *
 */

define([
  'jquery',
  './tabsbar',
  'page/ytree',
  'lodash/functions/throttle',
], function($, tabs, ytree, throttle) {
  'use strict';

  var $left = $('#left')
  var $treebox = $('#treebox')
  var $tree = $('#tree')
  var $title = $('#left-hd').children('.title')
  var $toggle = $('#left-hd').children('.toggle')
  // 计算 left 高度
  var layout = function() {
    var h = $left.height() - 30 // div#sites 高度明确是 60
    $treebox.height(h)
    // $tree.height(h)
  }

  layout()

  var tree = {
    init: function(data) {
      this.data = data
      menus.init(data)
      this.open('home')
    },
    open: function(menu) {
      var text =''
      var current = menus.current
      if (current) {
    	  if ($toggle.hasClass('toggled')) {
    		  if($('#J_menu_' + current+'_tab2').length>0){
    		     $('#J_menu_' + current+'_tab2').hide()
    		     $toggle.removeClass('toggled')
    		  }
    	      } else {
    	    	  $('#J_menu_' + current+'_tab1').hide()
    	      }
      }
      menus.current = menu
      text =$('#J_menu_'+menu+'_tab1').attr('name') 
      $title.text(text)
      if($('#J_menu_' + menu+'_tab2').length>0){
    	  $toggle.show()
      }else{
    	  $toggle.hide()
      }
      var $li = $('#J_menu_' + menu+'_tab1').show().children('.active')
        // 打开标签页
       $li.children('a').trigger('click')
       // $title.text(menus.topnav[menu])
    }
  }


  /**
   * 菜单
   *
   * 数据结构：
   *
   * [
   *   label: 菜单名字
   *   text: 菜单显示名
   *   children: [
   *     text: 菜单显示名
   *     url: 链接
   *   ]
   * ]
   *
   */
  var menus = {
    init: function(data) {
      this._topnav(data)
      this._render(data)
      this._bind( $('#tab1'))
      this._bind( $('#tab2'))
    },
    _topnav: function(data) {
      var html = ''
      var obj = {}
      var item

      for (var i = 0, len = data.length; i < len; i++) {
        item = data[i]
        obj[item.label] = item.text
        html += '<li><a href="javascript:;" data-label="' + item.label + '">' + item.text + '</a></li>'
      }
      $('#topnav').html(html)
      this.topnav = obj
    },
    _render: function(data) {
      var html_tab1 = ''
      var html_tab2 = ''
      var item_tab1
      var item_tab2
      for (var i = 0, len = data.length; i < len; i++) {
        item_tab1 = data[i].tab1
        html_tab1 += '<ul class="ytree ytree-wholerow" name="'+item_tab1.text+'"  id="J_menu_' + data[i].label + '_tab1" style="display: none;">'
        html_tab1 += this._ul(item_tab1.children, item_tab1.label) + '</ul>'
       if(data[i].tab2){
        item_tab2 = data[i].tab2
        html_tab2 += '<ul class="ytree ytree-wholerow" name="'+item_tab2.text+'"  id="J_menu_' + data[i].label + '_tab2" style="display: none;">'
        html_tab2 += this._ul(item_tab2.children, item_tab2.label) + '</ul>'
       }
      }
      $('#tab1').html(html_tab1)
      $('#tab2').html(html_tab2)
      $toggle.on('click', $.proxy(function(e) {
        this._toggleMenusite()
         e.stopPropagation()
        e.preventDefault()
       }, this))
    },
    // 递归生成 ul 内容
    _ul: function(nodes, parentRef, html) {
      html = html || ''
      parentRef = parentRef ? parentRef + '_' : ''
      for (var i = 0, len = nodes.length; i < len; i++) {
        var obj = $.extend({
          text: '',
          url: '#'
        }, nodes[i])
        var children = obj.children
        var ref = parentRef + i
        obj.ref = ref

        if (children) {
          obj.hasChildren = true
          html += this._li(obj)
          html = this._ul(children, ref, html) + '</ul></li>'
        } else {
          html += this._li(obj)
        }
      }
      return html
    },
    _li: function(node) {
      var classList = node.hasChildren ? ' class="b"' : ''
      var a = '<a class="a" href="' + node.url + '">' + node.text + '</a>'
      var li = '<li' + classList + ' data-ref="' + node.ref + '">' +
        '<p class="bg"></p>' +
        '<i class="oc"></i>' +
        a

      if (node.hasChildren) {
        li += '<ul>'
      } else {
        li += '</li>'
      }

      return li
    },
    _menuSite: function(ul) {
      this.$menuSite = $(ul).addClass('dropdown-menu').appendTo($treebox)
      
      $toggle.on('click', $.proxy(function(e) {
        this._toggleMenusite()
        e.preventDefault()
      }, this))
      
      this.$menuSite.on('click', 'a', $.proxy(function(e) {
        this._active(e.target)
        e.preventDefault()
      }, this))
    },
    _bind: function($menus_em) {
      // 打开标签页
    	$menus_em
        .on('click', 'a', $.proxy(function(e) {
          var a = e.target
          // 菜单项只是打开
          if ($(a).parent().hasClass('b')) {
            // this._toggle(a)
          } else {
            this._open(a)
          }
          e.preventDefault()
        }, this))
        .on('click', '.oc', $.proxy(function(e) {
            this._toggle(e.target)
        }, this))
        .on('mouseover', 'li', function(e) {
          $(this).addClass('hover')
          e.stopPropagation()
        })
        .on('mouseout', 'li', function(e) {
          $(this).removeClass('hover')
          e.stopPropagation()
        })
        .on('click', '.bg', function(e) {
          var $this = $(this)
          if ($this.parent().hasClass('b')) {
            $(this).siblings('.oc').trigger('click')
          } else {
            $(this).siblings('.a').trigger('click')
          }
        })
    },
    _open: function(elem) {
    	
      var $elem = $(elem)
      var $parent = $elem.parent('li')
      var $ifm = $('iframe[name="rightFrame"]')
      var link
      var active = 'active'
      //this.$menus.find('.' + active).removeClass(active)
        $('#tab1').find('.' + active).removeClass(active)
    	$('#tab2').find('.' + active).removeClass(active)
        $parent.addClass(active)
        link = {
          url: elem.href,
          title: $elem.text(),
          id: $parent.data('ref'),
          stamp: $.now()
        }
        tabs.open(link)
    },
    _toggle: function(elem) {
      $(elem).parent().toggleClass('open')
    },
    _toggleMenusite: function() {
    	
      var current = menus.current
      if($('#J_menu_' + current+'_tab2').length>0){
      if ($toggle.hasClass('toggled')) {
           $toggle.removeClass('toggled')
           $('#J_menu_' + current+'_tab2').hide()
           $('#J_menu_' + current+'_tab1').show()
           $title.text($('#J_menu_' + current+'_tab1').attr('name'))
      } else {
           $toggle.addClass('toggled')
           $('#J_menu_' + current+'_tab1').hide()
           $('#J_menu_' + current+'_tab2').show()
           $title.text($('#J_menu_' + current+'_tab2').attr('name'))
      }
      }
      return ;
    },
    _active: function(elem) {
      this._open(elem)
      $title.text(elem.title)
    }
  }

  /**
   * 栏目树
   *
   */
  var cates = {
    init: function(data) {
    	
      var $cates = $('#J_menu_portal_tab1')
      this.$cates = $cates
      this.tree = ytree($cates, {
        data: data
      })
      this._bind()
    },
    _bind: function() {
    	
      this.$cates.on('click', '.a', $.proxy(function(e) {
        this._open(e.target)
        e.preventDefault()
        e.stopPropagation();
      }, this))
    },
    _open: function(target) {
      var $li = $(target).parent()
      var active = 'active'
      var model = this.tree.model
      var url = APP + '?app=cms&m=Article&a=content'
      var ref = $li.data('ref')
      var sid = model[ref].sid
      var cid = model[ref].id
      url += '&sid=' + sid + '&cid=' + cid
      this.$cates.find('.' + active).removeClass(active)
      $li.addClass(active)

      tabs.open({
        url: url,
        title: '文章列表',
        id: 'frame_cates',
        stamp: $.now()
      })
    }
  }

  tree.cates = cates

  /**
   * 区块
   *
   */
  var blocks = {
    init: function() {
      this.$blocks = $('<div id="blocks" style="display:none"></div>').appendTo($treebox)
      $.getJSON(APP + '?app=cms&m=Cate&a=catesList')
        .done(function(data) {
          // 先缓存
          cates.data = data
        })
      var mytree = ytree(this.$blocks, {
        data: data
      })
    },
    bind: function() {

    }
  }

  $(window).on('resize', throttle(function() {
    layout()
  }, 50))

  // $(window).on('resize', function() {
  //   (throttle(function() {
  //     layout()
  //     setTimeout(function() {
  //       tree.scrollbar.refresh()
  //     }, 0)
  //   }, 50)())
  // })

  return tree
})
